namespace Skymate.Commands
{
    using System.Collections.Generic;

    using Abp.Events.Bus;

    using Skymate.Lyjt.Core;

    using SuperSocket.Common;

    /// <summary>
    /// 灯组查询应答
    /// </summary>
    public class LightGroupQueryResponseCommand : BaseLightCommand
    {
        public LightGroupQueryResponseCommand()
            : base(ProtocolConst.OptionType.QueryResponse, 
                ProtocolConst.ObjectType.SignalLampGroup)
        {
        }

        public override void ExecuteCommand(LightAppSession session, SemaphoreRequestInfo requestInfo)
        {
            var message = $"灯组查询应答";
            this.ShowLog(session.RemoteEndPoint.ToString(),
                message);
            
            var buffer = requestInfo.Body;
            var groups = this.GetLightGroupsWithBuffer(buffer);
            
            EventBus.Default.Trigger(new LightGroupQueryResponseEvent(
                session.RemoteEndPoint.ToString(),
                groups));
        }

        public IEnumerable<LightGroup> GetLightGroupsWithBuffer(byte[] buffer)
        {
            // 灯组数量
            var groupNumber = buffer[0];

            IList<LightGroup> groups = new List<LightGroup>();
            for (var i = 0; i < groupNumber; i++)
            {
                var group = LightGroup.Create(buffer.CloneRange(1+LightGroup.BufferLength*i, LightGroup.BufferLength));

                groups.Add(group);
            }
            return groups;
        }
    }
}